import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/ShopLogin.vue')
  },
  {
    path: '/',
    name: 'index',
    component: () => import('@/views/ShopIndex.vue'),
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        name: 'welcome',
        component: () => import('@/views/menu/WelcomePage.vue')
      },
      {
        path: '/users',
        name: 'users',
        component: () => import('@/views/menu/ShopUser.vue')

      },
      {
        path: '/roles',
        name: 'roles',
        component: () => import('@/views/menu/ShopRoles.vue')
      },
      {
        path: '/rights',
        name: 'rights',
        component: () => import('@/views/menu/ShopRights.vue')
      },
      {
        path: '/goods',
        name: 'goods',
        component: () => import('@/views/menu/ShopGoods.vue'),
      },
      {
        path: '/goods/add',
        name: 'add',
        component: () => import('@/views/menu/ShopAdd.vue')
      },
      {
        path: '/categories',
        name: 'categories',
        component: () => import('@/views/menu/ShopCategories.vue')
      },
      {
        path: '/params',
        name: 'params',
        component: () => import('@/views/menu/ShopParams.vue')
      },
      {
        path: '/orders',
        name: 'orders',
        component: () => import('@/views/menu/ShopOrders.vue')
      },
      {
        path: '/reports',
        name: 'reports',
        component: () => import('@/views/menu/ShopReports.vue')
      }
    ]
  }

]

let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
// push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  // if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originPush.call(this, location).catch(err => {return;})
}
// replace
VueRouter.prototype.replace = function replace (location, onResolve, onReject) {
  // if (onResolve || onReject) return originalReplace.call(this, location, onResolve, onReject)
  return originReplace.call(this, location).catch(err => err)
}

const router = new VueRouter({
  routes
})

const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  if (whiteList.includes(to.path)) return next()
  if (getToken()) return next()
  next('/login')
})

export default router
